package com.example.service.impl;

import com.example.common.Result;
import com.example.domain.thirdPartyQueryParam.ZhihuiyaKeywordSearchRequestParam;
import com.example.domain.thirdPartyResponseParam.ZhihuiyaApiSuccessResponse;
import com.example.domain.thirdPartyResponseParam.ZhihuiyaAuthenticationResponse;
import com.example.domain.thirdPartyResponseParam.ZhihuiyaErrorApiResponse;
import com.example.service.KeywordSearchService;
import com.example.util.HttpUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class KeywordSearchServiceImpl implements KeywordSearchService {

    public static final String zhihuiya_HOST = "https://connect.zhihuiya.com";
    public static final String zhihuiya_PATENT_SEARCH_PATH = "/search/patent/query-search-patent";
    public static final String zhihuiya_AUTHENTENTICATION_PATH = "/oauth/token";
    public static final String zhihuiya_PATENT_DETAILS_SEARCH_PATH = "/basic-patent-data/simple-bibliography";

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Result zhihuiyaAuthentication(String apiKey, String secretKey, Map headers, Map requestBody) {
        String host = "https://" + apiKey + ":" + secretKey +"@connect.zhihuiya.com";

        String queryResultStr = null;
        try {
            HttpResponse httpResponse = HttpUtils.doPost(host, zhihuiya_AUTHENTENTICATION_PATH, null, headers, null, requestBody);
            queryResultStr = EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(queryResultStr)) {
            return Result.error("请检测apikey或secretKey");
        }

        ZhihuiyaAuthenticationResponse.Data data = null;
        try {
            ZhihuiyaAuthenticationResponse zhihuiyaAuthenticationResponse
                    = objectMapper.readValue(queryResultStr, ZhihuiyaAuthenticationResponse.class);
            if (ObjectUtils.isEmpty(zhihuiyaAuthenticationResponse)) {
                return Result.error("请求参数序列化失败");
            }
            if (!zhihuiyaAuthenticationResponse.isStatus()) {
                // 如果相应结果为false，根据状态码响应的内容
                return Result.error(ObjectUtils.isEmpty(zhihuiyaAuthenticationResponse.getErrorMsg())
                        ? "错误代码: " + zhihuiyaAuthenticationResponse.getErrorCode()
                        : zhihuiyaAuthenticationResponse.getErrorMsg());
            }
            data = zhihuiyaAuthenticationResponse.getData();
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e.getMessage());
            return Result.error("请求参数序列化失败");
        }

        Map map = new HashMap();
        map.put("token", data.getToken());
        return Result.success(map);
    }

    @Override
    public Result queryPatentInfo(ZhihuiyaKeywordSearchRequestParam requestParam, Map headers, Map querys) {
        Integer page = requestParam.getOffset();
        Integer size = requestParam.getLimit();
        page = ObjectUtils.isEmpty(page) ? 1 : page;
        size = ObjectUtils.isEmpty(size) ? 10 : size;

        // 计算 offset
        requestParam.setOffset((page - 1) * size);
        requestParam.setLimit(size);

        String queryJsonStr;
        try {
            // 使用 ObjectMapper 进行 JSON 序列化
            queryJsonStr = objectMapper.writeValueAsString(requestParam);
        } catch (Exception e) {
            log.error("JSON序列化失败: {}", e.getMessage());
            return Result.error("请求参数序列化失败");
        }

        String queryResultStr = null;
        try {
            HttpResponse httpResponse =
                    HttpUtils.doPost(zhihuiya_HOST, zhihuiya_PATENT_SEARCH_PATH, null, headers, querys, queryJsonStr);
            queryResultStr = EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(queryResultStr)) {
            return Result.error("服务器内部出错");
        }

        ZhihuiyaApiSuccessResponse zhihuiyaApiSuccessResponse = null;
        try {
            // 首先解析 JSON 为 JsonNode
            JsonNode rootNode = objectMapper.readTree(queryResultStr);
            boolean status = rootNode.get("status").asBoolean();

            if (!status) {
                // 如果 status 为 false，解析为 ZhihuiyaErrorApiResponse
                ZhihuiyaErrorApiResponse errorResponse = objectMapper.readValue(queryResultStr, ZhihuiyaErrorApiResponse.class);
                // 处理错误响应
                if (ObjectUtils.isEmpty(errorResponse)) {
                    return Result.error("json转换异常");
                }
                // 如果相应结果为false，根据状态码响应的内容
                Result<Object> result = new Result<>();
                result.setCode(errorResponse.getErrorCode());
                result.setData(ObjectUtils.isEmpty(errorResponse.getErrorMsg())
                        ? "错误代码: " + errorResponse.getErrorCode()
                        : errorResponse.getErrorMsg());
                return result;
            }
            // 如果 status 为 true，解析为 ZhihuiyaApiSuccessResponse
            zhihuiyaApiSuccessResponse = objectMapper.readValue(queryResultStr, ZhihuiyaApiSuccessResponse.class);
        } catch (Exception e) {
            log.error("json转换异常: {}", e.getMessage());
            return Result.error("json转换异常");
        }

        // 如果 status 为 true，解析为 ZhihuiyaApiSuccessResponse
        // 处理成功响应
        if (ObjectUtils.isEmpty(zhihuiyaApiSuccessResponse)) {
            return Result.error("json转换异常");
        }
        List<ZhihuiyaApiSuccessResponse.Result> results = zhihuiyaApiSuccessResponse.getData().getResults();
        int totalSearchResultCount = zhihuiyaApiSuccessResponse.getData().getTotalSearchResultCount();


        Map map = new HashMap();
        map.put("results", results);
        map.put("totalSearchResultCount", totalSearchResultCount);
        return Result.success(map);
    }


}
